package com.jhgsys.internal.system.controller.app;

import com.jhgsys.internal.common.annotation.Limit;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.MD5Util;
import com.jhgsys.internal.monitor.entity.LoginLog;
import com.jhgsys.internal.monitor.service.IEhcacheService;
import com.jhgsys.internal.monitor.service.ILoginLogService;
import com.jhgsys.internal.system.dto.UserDto;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.IUserService;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.Map;

/**
 * @author MrBird
 */
@Validated
@RestController
@RequestMapping("app/common/")
public class AppLoginController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ILoginLogService loginLogService;

    @Autowired
    private IEhcacheService jedisUtils;

    @Value("${febs.shiro.session_timeout}")
    private Integer timeout;

    @PostMapping("login")
    @ResponseBody
    @Limit(key = "apiLogin", period = 60, count = 30, name = "接口用户登录接口", prefix = "limit")
    public FebsResponse webSiteLogin(@NotBlank(message = "{required}") String userName,
                                     @NotBlank(message = "{required}") String password) {
        try {
            password = MD5Util.encrypt(userName.toLowerCase(), password);
            UsernamePasswordToken token = new UsernamePasswordToken(userName, password, false);
            try {
                super.login(token);
                User user = userService.findByName(userName);
                // 保存登录日志
                LoginLog loginLog = new LoginLog();
                loginLog.setUserName(userName);
                loginLog.setSystemBrowserInfo();
                this.loginLogService.saveLoginLog(loginLog);


//                //token信息
//                 String tokenResult = TokenUtils.createJWT(userName, -1);
//                jedisUtils.set(tokenResult, ""+ getSubject().getSession().getId(), timeout);
                Map<String, Object> retMap = new HashMap();
                user.setPassword("");
//                retMap.put("appToken", tokenResult);
                retMap.put("user", BeanHelper.copyProperties(user, UserDto.class));
                return new FebsResponse().success().data(retMap);
            } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e) {
                throw new FebsException(e.getMessage());
            } catch (AuthenticationException e) {
                throw new FebsException("认证失败！");
            }
        } catch (Exception e) {
            return new FebsResponse().fail().message(e.getMessage());
        }
    }

}
